package com.sgy.zookeeper_api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class DeleteNote implements Watcher {

    // 允许等待一个线程
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /*
        建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        /*
        * connectString：连接地址（ip:port）
        * sessionTimeout：会话超时时间
        * watcher：监听器
        * */
        zooKeeper = new ZooKeeper("192.168.201.129:2181", 30000, new DeleteNote());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent.getState());
        // SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 删除节点
            try {
                deleteNoteSync();
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 删除节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    private void deleteNoteSync() throws KeeperException, InterruptedException {
        /*
            zooKeeper.exists(path,watch) :判断节点是否存在
            zookeeper.delete(path,version) : 删除节点
        */
        Stat exists = zooKeeper.exists("/zk-persisent/c10000000000", false);
        System.out.println(exists == null ? "该节点不存在" : "该节点存在");
        if (exists != null) {
            zooKeeper.delete("/zk-persisent/c10000000000", -1);
        }
        Stat exists2 = zooKeeper.exists("/zk-persisent/c10000000000", false);
        System.out.println(exists2 == null ? "该节点不存在" : "该节点存在");
    }
}
